package com.jackeysun.util

import com.google.gson.Gson
import com.google.gson.GsonBuilder
import com.google.gson.reflect.TypeToken
import java.lang.IllegalArgumentException
import java.util.*

val GSON: Gson = GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").disableHtmlEscaping().create()
inline fun <reified T> String.toObject(block: () -> Gson): T {
    return block().fromJson(this, object : TypeToken<T>() {}.type)
}

inline fun <reified T> T.toJson(block: () -> Gson): String {
    return block().toJson(this)
}

inline fun <reified T> String.toObject(): T {
    return this.toObject { GSON }
}

inline fun <reified T> T.toJson(): String {
    return this.toJson { GSON }
}


val RANDOM = Random()
fun Int.randomTo(end: Int): Int {
    return if (end > this) {
        RANDOM.random(this, end.minus(this))
    } else {
        throw IllegalArgumentException("请输入大于初始值的整数")
    }
}

fun IntRange.random(): Int {
    return if (this.last > this.first) {
        RANDOM.random(this.first, this.last.minus(this.first))
    } else {
        throw IllegalArgumentException("请输入大于初始值的整数")
    }
}

/**
 * 随机数范围[start,start+plus)
 */
fun Random.random(start: Int, plus: Int): Int {
    return try {
        this.nextInt(plus).plus(start)
    } catch (e: Exception) {
        start
    }
}